<?php
namespace app\home\logic;

use think\Model;
use think\db;

class Sign extends Model {
    //送积分
    function sign($data = []) {
        if (!isset($data['user_id'])) {
            return ['code' => 0, 'msg' => '用户ID不能为空!'];
        }
        $model = model('sign');
        $re = $model->getSign($data['user_id']);
        if ($re > 0) {
            return ['code' => 0, 'msg' => '您已签到!'];
        }
        //开启事务
        Db::startTrans();

        $id = $model->add([
                'user_id' => $data['user_id']
        ]);
        if (!$id) {
            Db::rollback();
            return ['code' => 0, 'msg' => '签到失败'];
        }
        $result = model('credit_type')->getOne(['nid' => 'sign']);
        $credit = $result['value'] ?: 0;

        //更新账户积分
        $_result = model('account')->getOne(['user_id' => $data['user_id']]);
        $re = model('account')->updateBalanceJf([
                'user_id' => $data['user_id'],
                'score' => $credit,
        ]);
        if (!$re) {
            Db::rollback();
            return ['code' => 0, 'msg' => '更新账户积分失败'];
        }
        Db::commit();

        $jfnid = "sign_" . $data['user_id'] . "_" . time();
        $balance_jf = $_result['balance_jf'] + $credit;

        //每日签到积分日志
        model('jf_log')->add([
                'userid' => $data['user_id'],
                'nid' => $jfnid,
                'run_jf' => $credit,
                'balance_jf' => $balance_jf,
                'baizhu' => '签到所得积分'
        ]);

        //赠送签到积分
        $credit_log['user_id'] = $data['user_id'];
        $credit_log['nid'] = "sign";
        $credit_log['code'] = "credit";
        $credit_log['type'] = "sign";
        $credit_log['addtime'] = time();
        $credit_log['article_id'] = $id;
        $credit_log['remark'] = "签到所得积分";
        model('credit', 'logic')->ActionCreditLog($credit_log);

        return ['status' => 1, 'jifen' => $credit, 'msg' => '签到成功', 'balance' => $balance_jf];
    }
}